<template>
  <div class="users-page">
    <!-- 页面标题 -->
    <t-card class="header-card">
      <div class="card-header">
        <h2 class="page-title">用户管理</h2>
        <t-space>
          <t-button theme="primary" @click="handleCreateUser">
            <template #icon><t-icon name="add" /></template>
            新增用户
          </t-button>
        </t-space>
      </div>
    </t-card>
    
    <!-- 搜索和筛选 -->
    <t-card class="filter-card">
      <t-form layout="inline" :data="searchForm" @reset="handleSearchReset" @submit="handleSearchSubmit">
        <t-form-item label="用户名/姓名" name="keyword">
          <t-input
            v-model="searchForm.keyword"
            placeholder="请输入用户名或姓名"
            clearable
          />
        </t-form-item>
        <t-form-item label="角色" name="role">
          <t-select
            v-model="searchForm.role"
            placeholder="请选择角色"
            clearable
            style="width: 150px"
          >
            <t-option
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </t-select>
        </t-form-item>
        <t-form-item label="状态" name="status">
          <t-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <t-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </t-select>
        </t-form-item>
        <t-form-item>
          <t-space>
            <t-button theme="primary" type="submit">
              <template #icon><t-icon name="search" /></template>
              搜索
            </t-button>
            <t-button theme="default" type="reset">重置</t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </t-card>
    
    <!-- 用户列表表格 -->
    <t-card class="table-card">
      <t-table
        :data="userList"
        :columns="columns"
        :row-key="rowKey"
        :loading="tableLoading"
        :pagination="pagination"
        :hover="true"
        @page-change="onPageChange"
      >
        <!-- 用户名列 -->
        <template #username="{ row }">
          <div class="user-username">
            {{ row.username }}
          </div>
        </template>
        
        <!-- 姓名和头像列 -->
        <template #name="{ row }">
          <div class="user-info">
            <t-avatar :image="row.avatar" :size="40">
              <template v-if="!row.avatar">{{ row.name.substring(0, 1) }}</template>
            </t-avatar>
            <span class="user-name">{{ row.name }}</span>
          </div>
        </template>
        
        <!-- 角色列 -->
        <template #role="{ row }">
          <t-tag theme="default" variant="light">{{ getRoleLabel(row.role) }}</t-tag>
        </template>
        
        <!-- 状态列 -->
        <template #status="{ row }">
          <t-tag :theme="getStatusTheme(row.status)">
            {{ getStatusLabel(row.status) }}
          </t-tag>
        </template>
        
        <!-- 最后登录时间列 -->
        <template #lastLoginTime="{ row }">
          {{ formatDate(row.lastLoginTime) }}
        </template>
        
        <!-- 操作列 -->
        <template #operation="{ row }">
          <t-space>
            <t-link theme="primary" hover="color" @click="handleEditUser(row)">编辑</t-link>
            <t-link theme="primary" hover="color" @click="handleViewDetail(row)">查看</t-link>
            <t-dropdown :options="getStatusOptions(row)" @click="handleStatusChange(row, $event)">
              <t-link theme="primary" hover="color">更改状态</t-link>
            </t-dropdown>
            <t-link
              theme="primary"
              hover="color"
              @click="handleResetPassword(row)"
            >
              重置密码
            </t-link>
            <t-popconfirm
              content="确认删除该用户吗？该操作不可撤销。"
              @confirm="handleDeleteUser(row)"
            >
              <t-link theme="danger" hover="color">删除</t-link>
            </t-popconfirm>
          </t-space>
        </template>
      </t-table>
    </t-card>
    
    <!-- 用户表单对话框 -->
    <t-dialog
      v-model:visible="dialogVisible"
      :header="formMode === 'create' ? '新增用户' : '编辑用户'"
      width="600px"
      :footer="false"
      @close="resetForm"
    >
      <t-form
        ref="form"
        :data="formData"
        :rules="rules"
        :label-width="100"
        @submit="handleFormSubmit"
      >
        <t-form-item label="用户名" name="username">
          <t-input v-model="formData.username" placeholder="请输入用户名" :disabled="formMode === 'edit'" />
        </t-form-item>
        <t-form-item label="姓名" name="name">
          <t-input v-model="formData.name" placeholder="请输入姓名" />
        </t-form-item>
        <t-form-item v-if="formMode === 'create'" label="密码" name="password">
          <t-input
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
          />
        </t-form-item>
        <t-form-item label="邮箱" name="email">
          <t-input v-model="formData.email" placeholder="请输入邮箱" />
        </t-form-item>
        <t-form-item label="手机号" name="phone">
          <t-input v-model="formData.phone" placeholder="请输入手机号" />
        </t-form-item>
        <t-form-item label="部门" name="department">
          <t-input v-model="formData.department" placeholder="请输入部门" />
        </t-form-item>
        <t-form-item label="角色" name="role">
          <t-select
            v-model="formData.role"
            placeholder="请选择角色"
          >
            <t-option
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </t-select>
        </t-form-item>
        <t-form-item label="状态" name="status">
          <t-radio-group v-model="formData.status">
            <t-radio value="active">启用</t-radio>
            <t-radio value="inactive">禁用</t-radio>
          </t-radio-group>
        </t-form-item>
        <t-form-item>
          <t-space>
            <t-button theme="default" @click="dialogVisible = false">取消</t-button>
            <t-button theme="primary" type="submit" :loading="submitLoading">确定</t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </t-dialog>
    
    <!-- 用户详情对话框 -->
    <t-dialog
      v-model:visible="detailVisible"
      header="用户详情"
      width="600px"
      :footer="false"
    >
      <div class="user-detail" v-if="detailData">
        <div class="detail-header">
          <t-avatar :image="detailData.avatar" :size="80">
            <template v-if="!detailData.avatar">{{ detailData.name.substring(0, 1) }}</template>
          </t-avatar>
          <div class="detail-title">
            <h3>{{ detailData.name }}</h3>
            <div class="detail-subtitle">{{ detailData.username }}</div>
          </div>
        </div>
        <div class="detail-content">
          <t-descriptions layout="vertical" :data="getUserDetailData()" :column="2" />
        </div>
      </div>
    </t-dialog>
    
    <!-- 重置密码结果对话框 -->
    <t-dialog
      v-model:visible="passwordVisible"
      header="密码重置成功"
      width="400px"
      :footer="false"
    >
      <div class="password-reset">
        <div class="password-title">
          <t-icon name="check-circle-filled" style="color: #00a870; font-size: 24px; margin-right: 8px;"></t-icon>
          <span>密码已重置</span>
        </div>
        <div class="password-content">
          <p>新密码：<t-tag theme="default">{{ newPassword }}</t-tag></p>
          <p class="password-tip">请妥善保管密码，并通知用户尽快修改密码！</p>
        </div>
        <div class="password-footer">
          <t-button theme="primary" @click="copyPassword">复制密码</t-button>
          <t-button theme="default" @click="passwordVisible = false">关闭</t-button>
        </div>
      </div>
    </t-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import type { PrimaryTableCol, TableRowData, PageInfo, DropdownOption } from 'tdesign-vue-next'
import {
  getUsers,
  getUserDetail,
  createUser,
  updateUser,
  deleteUser,
  updateUserStatus,
  resetUserPassword,
  getRoles,
  type User,
  type UserFormData
} from '../../api/users'

// 表格列定义
const columns: PrimaryTableCol[] = [
  {
    colKey: 'name',
    title: '姓名',
    width: 160,
    cell: 'name'
  },
  {
    colKey: 'username',
    title: '用户名',
    width: 120,
    cell: 'username'
  },
  {
    colKey: 'department',
    title: '部门',
    width: 120
  },
  {
    colKey: 'phone',
    title: '手机号',
    width: 120
  },
  {
    colKey: 'email',
    title: '邮箱',
    width: 180
  },
  {
    colKey: 'role',
    title: '角色',
    width: 100,
    cell: 'role'
  },
  {
    colKey: 'status',
    title: '状态',
    width: 100,
    cell: 'status'
  },
  {
    colKey: 'lastLoginTime',
    title: '最后登录时间',
    width: 160,
    cell: 'lastLoginTime'
  },
  {
    colKey: 'operation',
    title: '操作',
    fixed: 'right',
    width: 240,
    cell: 'operation'
  }
]

// 表格数据
const userList = ref<User[]>([])
const tableLoading = ref(false)
const rowKey = 'id'

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 搜索表单
const searchForm = reactive({
  keyword: '',
  role: '',
  status: ''
})

// 角色选项
const roleOptions = ref<Array<{value: string, label: string}>>([
  { value: 'admin', label: '管理员' },
  { value: 'operator', label: '运营' },
  { value: 'editor', label: '编辑' },
  { value: 'viewer', label: '查看者' }
])

// 状态选项
const statusOptions = [
  { value: 'active', label: '启用' },
  { value: 'inactive', label: '禁用' },
  { value: 'locked', label: '锁定' }
]

// 表单数据
const formMode = ref<'create' | 'edit'>('create')
const dialogVisible = ref(false)
const submitLoading = ref(false)
const form = ref(null)

// 详情数据
const detailVisible = ref(false)
const detailData = ref<User | null>(null)

// 密码重置
const passwordVisible = ref(false)
const newPassword = ref('')

// 表单初始化数据
const defaultFormData: UserFormData = {
  username: '',
  name: '',
  password: '',
  email: '',
  phone: '',
  role: 'viewer',
  status: 'active',
  department: ''
}

// 表单数据
const formData = reactive<UserFormData>({ ...defaultFormData })

// 表单验证规则
const rules = {
  username: [{ required: true, message: '请输入用户名', type: 'error' }],
  name: [{ required: true, message: '请输入姓名', type: 'error' }],
  password: [{ required: true, message: '请输入密码', type: 'error' }],
  role: [{ required: true, message: '请选择角色', type: 'error' }],
  email: [{ pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '请输入正确的邮箱', type: 'error' }],
  phone: [{ pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', type: 'error' }]
}

// 初始化数据
onMounted(() => {
  fetchUserList()
  fetchRoles()
})

// 获取用户列表
const fetchUserList = async () => {
  tableLoading.value = true
  try {
    const { data } = await getUsers({
      page: pagination.current,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword || undefined,
      role: searchForm.role || undefined,
      status: searchForm.status || undefined
    })
    
    // 数据处理
    userList.value = data || []
    pagination.total = data?.length || 0
  } catch (error) {
    console.error('获取用户列表失败', error)
    MessagePlugin.error('获取用户列表失败')
  } finally {
    tableLoading.value = false
  }
}

// 获取角色列表
const fetchRoles = async () => {
  try {
    const { data } = await getRoles()
    if (data && data.length > 0) {
      roleOptions.value = data
    }
  } catch (error) {
    console.error('获取角色列表失败', error)
  }
}

// 格式化日期
const formatDate = (dateStr?: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 获取角色标签
const getRoleLabel = (value: string) => {
  const role = roleOptions.value.find(item => item.value === value)
  return role ? role.label : value
}

// 获取状态标签
const getStatusLabel = (status: User['status']) => {
  const statusMap: Record<User['status'], string> = {
    active: '启用',
    inactive: '禁用',
    locked: '锁定'
  }
  return statusMap[status] || status
}

// 获取状态主题色
const getStatusTheme = (status: User['status']) => {
  const themeMap: Record<User['status'], 'default' | 'primary' | 'warning' | 'success' | 'danger'> = {
    active: 'success',
    inactive: 'default',
    locked: 'warning'
  }
  return themeMap[status] || 'default'
}

// 获取用户状态操作选项
const getStatusOptions = (user: User): DropdownOption[] => {
  const options: DropdownOption[] = []
  
  if (user.status !== 'active') {
    options.push({ content: '启用', value: 'active' })
  }
  
  if (user.status !== 'inactive') {
    options.push({ content: '禁用', value: 'inactive' })
  }
  
  if (user.status !== 'locked') {
    options.push({ content: '锁定', value: 'locked' })
  }
  
  return options
}

// 处理状态变更
const handleStatusChange = async (user: User, dropdownItem: { value: string }) => {
  const status = dropdownItem.value as User['status']
  
  try {
    await updateUserStatus(user.id, status)
    MessagePlugin.success(`用户已${getStatusLabel(status)}`)
    fetchUserList()
  } catch (error) {
    console.error('更新用户状态失败', error)
    MessagePlugin.error('更新用户状态失败')
  }
}

// 获取用户详情数据
const getUserDetailData = () => {
  if (!detailData.value) return []
  
  return [
    { label: '用户名', content: detailData.value.username },
    { label: '姓名', content: detailData.value.name },
    { label: '邮箱', content: detailData.value.email || '-' },
    { label: '手机号', content: detailData.value.phone || '-' },
    { label: '部门', content: detailData.value.department || '-' },
    { label: '角色', content: getRoleLabel(detailData.value.role) },
    { label: '状态', content: getStatusLabel(detailData.value.status) },
    { label: '创建时间', content: formatDate(detailData.value.createTime) },
    { label: '最后登录', content: formatDate(detailData.value.lastLoginTime) }
  ]
}

// 分页变化
const onPageChange = (pageInfo: PageInfo) => {
  pagination.current = pageInfo.current
  pagination.pageSize = pageInfo.pageSize
  fetchUserList()
}

// 搜索表单提交
const handleSearchSubmit = () => {
  pagination.current = 1
  fetchUserList()
}

// 搜索表单重置
const handleSearchReset = () => {
  pagination.current = 1
  fetchUserList()
}

// 创建用户
const handleCreateUser = () => {
  formMode.value = 'create'
  Object.assign(formData, defaultFormData)
  dialogVisible.value = true
}

// 编辑用户
const handleEditUser = async (row: User) => {
  formMode.value = 'edit'
  dialogVisible.value = true
  submitLoading.value = true
  
  try {
    const { data } = await getUserDetail(row.id)
    if (data) {
      // 填充表单数据，但不包括密码
      formData.id = data.id
      formData.username = data.username
      formData.name = data.name
      formData.email = data.email || ''
      formData.phone = data.phone || ''
      formData.role = data.role
      formData.status = data.status === 'locked' ? 'inactive' : data.status
      formData.department = data.department || ''
    }
  } catch (error) {
    console.error('获取用户详情失败', error)
    MessagePlugin.error('获取用户详情失败')
    dialogVisible.value = false
  } finally {
    submitLoading.value = false
  }
}

// 查看用户详情
const handleViewDetail = async (row: User) => {
  try {
    const { data } = await getUserDetail(row.id)
    if (data) {
      detailData.value = data
      detailVisible.value = true
    }
  } catch (error) {
    console.error('获取用户详情失败', error)
    MessagePlugin.error('获取用户详情失败')
  }
}

// 重置密码
const handleResetPassword = async (row: User) => {
  try {
    const { data } = await resetUserPassword(row.id)
    if (data) {
      newPassword.value = data.password
      passwordVisible.value = true
    }
  } catch (error) {
    console.error('重置密码失败', error)
    MessagePlugin.error('重置密码失败')
  }
}

// 复制密码
const copyPassword = () => {
  // 使用Clipboard API进行复制
  navigator.clipboard.writeText(newPassword.value)
    .then(() => {
      MessagePlugin.success('密码已复制到剪贴板')
    })
    .catch(() => {
      MessagePlugin.error('复制失败，请手动复制')
    })
}

// 删除用户
const handleDeleteUser = async (row: User) => {
  try {
    await deleteUser(row.id)
    MessagePlugin.success('删除成功')
    fetchUserList()
  } catch (error) {
    console.error('删除用户失败', error)
    MessagePlugin.error('删除用户失败')
  }
}

// 提交表单
const handleFormSubmit = async () => {
  submitLoading.value = true
  try {
    if (formMode.value === 'create') {
      await createUser(formData)
      MessagePlugin.success('创建成功')
    } else {
      const { password, ...updateData } = formData
      await updateUser(formData.id!, updateData)
      MessagePlugin.success('更新成功')
    }
    dialogVisible.value = false
    fetchUserList()
  } catch (error) {
    console.error('提交失败', error)
    MessagePlugin.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, defaultFormData)
}
</script>

<style scoped>
.users-page {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.filter-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-name {
  font-weight: 500;
}

.user-username {
  font-family: monospace;
}

.detail-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;
}

.detail-title h3 {
  margin: 0 0 4px 0;
  font-size: 18px;
}

.detail-subtitle {
  color: rgba(0, 0, 0, 0.6);
  font-size: 14px;
}

.detail-content {
  margin-top: 16px;
}

.password-reset {
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.password-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 500;
}

.password-content {
  padding: 16px;
  background-color: rgba(0, 0, 0, 0.02);
  border-radius: 8px;
}

.password-tip {
  margin-top: 8px;
  color: rgba(0, 0, 0, 0.6);
  font-size: 14px;
}

.password-footer {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}
</style>
 